package com.tiantian;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 启动完成后的初使化
 *
 * @author wangkai
 * @since 2020/12/4.
 */
@Component
public class StartedCallback implements CommandLineRunner, ApplicationListener<WebServerInitializedEvent> {
    private static final Logger log = LoggerFactory.getLogger(StartedCallback.class);
    @Autowired
    private Environment env;
    private int port;

    @Override
    public void run(String... args) throws Exception {
        String host = null;
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("获取本机IP出错：", e);
            host = "localhost";
        }
        String appName = env.getProperty("spring.application.name");
        String context = env.getProperty("server.servlet.context-path", "");
        log.info("\n----------------------------------------------------------\n" +
                        "Application '{}' is running! Access URLs:\n" +
                        "Local: \t\t http://localhost:{}{}\n" +
                        "Network: \t http://{}:{}{}\n" +
                        "Doc: \t\t http://{}:{}{}/swagger-ui.html" +
                        "\n----------------------------------------------------------",
                appName,
                port, context,
                host, port, context,
                host, port, context);
        log.info("\n******************************************************" +
                "\nAPPLICATION SUCCESSED TO START on ports(s):" + port +
                "\n******************************************************");
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.port = event.getWebServer().getPort();
    }
}
